
//
// 110109a- AH - Created.
// 110109b- AH - treeToString().
// 120118 - AH - (Garage) getLast().
//

package org.soekrat.engine.wheel.retrieval;

import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *   TODO
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
public final class RetrievalEventTree 
{
  private final List<RetrievalEvent> m_roots=new ArrayList<RetrievalEvent>();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public RetrievalEventTree(){}
  
  /**
   * <p>
   *   Adds root.
   * </p>
   * @param root Root.
   */
  public void addRoot(RetrievalEvent root)
  {
    if (root==null)
    {
      throw new NullPointerException("root");
    }
    
    m_roots.add(root);
  }
  
  /**
   * <p>
   *   Gets number of roots.
   * </p>
   * @return Roots.
   */
  public int size(){ return m_roots.size(); }
  
  /**
   * <p>
   *   Gets
   *   {@link RetrievalEvent} root.
   * </p>
   * @param idx Index of root event.
   * @return Root event.
   * @throws IndexOutOfBoundsException If {@code idx<0 || idx>=size()}.
   */
  public RetrievalEvent get(int idx){ return m_roots.get(idx); }
  
  /**
   * <p>
   *   Gets last root event.
   * </p>
   * @return Last or {@code null} if has no events.
   */
  public RetrievalEvent getLast()
  {
    int size=m_roots.size();
    
    if (size==0) return null;
    
    return m_roots.get(size-1);
  }
  
  /**
   * <p>
   *   Gets index of an event.
   * </p>
   * @param e {@link RetrievalEvent} to get index of.
   * @return Index or {@code -1} if not found.
   */
  public int indexOf(RetrievalEvent e)
  {
    if (e==null)
    {
      throw new NullPointerException("e");
    }
    
    return m_roots.indexOf(e);
  }
  
  /**
   * <p>
   *   Gets
   *   {@code String} presentation of tree.
   * </p>
   * @return Presentation.
   */
  public String treeToString()
  {
    CharArrayWriter caw=new CharArrayWriter();
    PrintWriter pw=new PrintWriter(caw);
    
    for (RetrievalEvent curr : m_roots)
    {
      pw.println(curr.sequenceToString());  
    }
    
    pw.flush();
    return caw.toString();
  }
  
}
